package com.jwtsecurity.config.security;

import com.alibaba.fastjson.JSON;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class SecurityFailureHandler extends SimpleUrlAuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure
            (HttpServletRequest req, HttpServletResponse res, AuthenticationException e)
            throws IOException, ServletException {
        Map<String,Object> map = new HashMap<>();
        res.setContentType("application/json;charset=UTF-8;");
        String errorMsg = "用户或密码错误",code = "5001";
        map.put("code",code);
        map.put("msg",errorMsg);
        res.getWriter().write(JSON.toJSONString(map));
    }
}
